<?php

/**
 * @author 	: Le Nguyen Thien An <thienan289@gmail.com>
 */

interface AdminHelper
{
	public function getViewRightMenu($adminId);
	public function getIndexRightMenu();
	public function getShowAdminQueryCondition();
	public function checkAllowUpdate($adminId);
}

abstract class AbstractAdminHelper implements AdminHelper
{
	protected function getDefaultViewRightMenu($adminId)
	{
		return array(
					array('label'=>'List Administator', 'url'=>array('index')),
					array('label'=>'Update Administator', 'url'=>array('update', 'id'=> $adminId)),
		);
	}
}

class DefaultAdminHelper extends AbstractAdminHelper 
{
	public function getViewRightMenu($adminId)
	{
		$defaultMenu = $this->getDefaultViewRightMenu($adminId);
		return $defaultMenu;
	}
	public function getIndexRightMenu()
	{
		return array();
	}

	public function getShowAdminQueryCondition()
	{
		$userId = Yii::app()->user->id;
		return "status = 1 and id = ".$userId;
	}

	public function checkAllowUpdate($adminId)
	{
		$userId = Yii::app()->user->id;
		if (strval($userId) === strval($adminId))
		{
			return true;
		}
		return false;
	}
}

class SuperAdminHelper extends AbstractAdminHelper 
{
	public function getViewRightMenu($adminId)
	{

		$defaultMenu = $this->getDefaultViewRightMenu($adminId);
		$superAdminMenu = array(
							array('label'=>'Create Administator', 'url'=>array('create')),
							array('label'=>'Delete Administator', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$adminId),'confirm'=>'Are you sure you want to delete this item?')),
						);
		return array_merge($superAdminMenu, $defaultMenu);
	}

	public function getIndexRightMenu()
	{
		return array(
			array('label'=>'Create Administator', 'url'=>array('create')),
		);
	}
	public function getShowAdminQueryCondition()
	{
		return "status = 1";
	}

	public function checkAllowUpdate($adminId)
	{
		return true;
	}
}

class AdminHelperFactory
{
	public static function createInstance()
	{
		$user = yii::app()->user;
		if ($user->checkAccess(AdministatorController::ROLE_SUPER_ADMINISTATOR))
		{
			return new SuperAdminHelper();
		}
		else if ($user->checkAccess(AdministatorController::ROLE_ADMINISTATOR))
		{
			return new DefaultAdminHelper();
		}
		return null;
	}
}

class AdministatorController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	const ROLE_ADMINISTATOR 			= "administator";
	const ROLE_SUPER_ADMINISTATOR		= "super_administator";

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index','view', 'update'),
				'roles'=>array(self::ROLE_ADMINISTATOR),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create', 'delete'),
				'roles'=>array(self::ROLE_SUPER_ADMINISTATOR),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);

		$rightMenu = array();
		$adminHelper = AdminHelperFactory::createInstance();
		if (isset($adminHelper))
		{
			$rightMenu = $adminHelper->getViewRightMenu($model->id);
		}

		$this->render('view',array(
			'model'=> $model, 'rightMenu' => $rightMenu
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Administator;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Administator']))
		{
			$model->attributes=$_POST['Administator'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		
		$adminHelper = AdminHelperFactory::createInstance();
		$isInvalid = false;

		if (isset($adminHelper))
		{
			if (!$adminHelper->checkAllowUpdate($id))
			{
				$isInvalid = true;
			}
		}		
		else
		{
			$isInvalid = true;
		}

		if ($isInvalid === true)
		{
			throw new CHttpException("404", "the requested page does not exist");
		}

		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Administator']))
		{
			$model->attributes=$_POST['Administator'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$model->password = '';
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
		if(!isset($_GET['ajax']))
		{
			$this->redirect(array('index'));
		}
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		//if(!isset($_GET['ajax']))
			//$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$rightMenu = array();
		$adminHelper = AdminHelperFactory::createInstance();
		$condition = "";
		if (isset($adminHelper))
		{
			$rightMenu = $adminHelper->getIndexRightMenu();
			$condition = $adminHelper->getShowAdminQueryCondition();
		}

		$dataProvider=new CActiveDataProvider('Administator', array(
			'criteria'=>array(
        		'condition'=> $condition,
        		'order'=>'username ASC'
    		)
		));

		$this->render('index',array(
			'dataProvider'=>$dataProvider, "rightMenu" => $rightMenu
		));
	}

	/**
	 * Manages all models.
	 */
	/*
	public function actionAdmin()
	{
		$model=new Administator('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Administator']))
			$model->attributes=$_GET['Administator'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	*/
	
	public function actionInit()
	{
		$connection = Yii::app()->db;
		$transaction=$connection->beginTransaction();

		try
		{
			$command = $connection->createCommand();
			$command->truncateTable("dnd_boxanhfood_authassignment");
			$command->truncateTable("dnd_boxanhfood_authitemchild");
			$command->truncateTable("dnd_boxanhfood_authitem");
			//$command->truncateTable("dnd_boxanhfood_administator");
/*
			$admin = new Administator;
			$admin->attributes = array('username' => 'admin', 'password' => '123456' , "password_repeat" => '123456');

			if (!$admin->save())
			{
				 throw new Exception('Failed to create admin.');
			}
			$adminId = $admin->primaryKey;
			$auth = Yii::app()->authManager;

			//$auth->createOperation("createAdmin");
			//$auth->createOperation("readAdmin");
			//$auth->createOperation("updateAdmin");
			//$auth->createOperation("deleteAdmin");

			$adminRole = $auth->createRole(self::ROLE_ADMINISTATOR);
			//$adminRole->addChild("readAdmin");
			//$adminRole->addChild("updateAdmin");

			$superAdminRole = $auth->createRole(self::ROLE_SUPER_ADMINISTATOR);
			//$superAdminRole->addChild("createAdmin");
			//$superAdminRole->addChild("deleteAdmin");
			//$superAdminRole->addChild("administator");

			$superAdminRole->addChild(self::ROLE_ADMINISTATOR);

			$auth->assign(self::ROLE_SUPER_ADMINISTATOR, $adminId);

			//yii::trace($adminId, "dnd.all");
*/
			$transaction->commit();
			$this->renderText("ActionInit - commit");
		}
		catch(Exception $e)
		{
   			$transaction->rollback();
   			$this->renderText($e->getMessage());
		}
		
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Administator the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Administator::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Administator $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='administator-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
